<template>
  <div id="work_view">
    <div class="work_search_model">
      <div class="work_progress">
        <el-tooltip
          effect="dark"
          content="作业完成度：完成作业/全部作业"
          placement="bottom"
        >
          <el-progress
            :text-inside="true"
            :stroke-width="26"
            :percentage="finishRating"
          ></el-progress>
        </el-tooltip>
      </div>

      <div class="work_search">
        <div class="work_search_input">
          <input
            type="text"
            v-model="searchValue"
            @keyup.enter="searchWorkByCourseName"
            placeholder="输入课程名字Search..."
          />
        </div>
        <div class="work_search_img" style="background-color: #c064f9">
          <img
            :src="searchImgUrl"
            alt=""
            style="width: 51px; margin-left: -1%"
          />
        </div>
      </div>

      <div class="work_search_btn" @click="getData('uncommited')">
        <el-tooltip
          effect="dark"
          content="查看未提交的作业"
          placement="bottom-start"
        >
          <img :src="noDoImgUrl" alt="" />
        </el-tooltip>
      </div>

      <div class="work_search_btn" @click="getData('commited')">
        <el-tooltip
          effect="dark"
          content="查看已做作业"
          placement="bottom-start"
        >
          <img :src="doneImgUrl" alt="" />
        </el-tooltip>
      </div>

      <div class="work_search_btn" @click="getData('timeout')">
        <el-tooltip
          effect="dark"
          content="查看已过期作业"
          placement="bottom-start"
        >
          <img :src="timoutImgUrl" alt="" />
        </el-tooltip>
      </div>

      <div class="work_search_btn" @click="getData('all')">
        <el-tooltip
          effect="dark"
          content="查看全部作业"
          placement="bottom-start"
        >
          <img :src="allImgUrl" alt="" />
        </el-tooltip>
      </div>
    </div>

    <div class="work_main">
      <div
        :class="work.end == 0 ? 'item' : 'item work_timout'"
        v-for="(work) in works"
        :key="work.workId"
      >
        <div class="work_top_img">
          <img :src="workImgUrl" alt="" />
        </div>
        <div class="work_info">
          <div class="work_info_header">
            {{ work.workName }} - 课程名：{{ work.courseName }} <br />
            <i class="el-icon-time"></i> 开始时间：{{ work.startTime }} <br />
            <i class="el-icon-time"></i> 结束时间：{{ work.endTime }} <br />
            <el-tag>{{ work.workType == 1 ? "文本题" : "选择题" }}</el-tag>
          </div>

          <div class="ql-snow" v-if="work.contentType == 1">
            <div class="ql-editor" v-html="work.content"></div>
          </div>

          <div v-if="work.contentType == 2" style="margin-top: 10px">
            <el-image
              :src="work.workImgUrl"
              :preview-src-list="[work.workImgUrl]"
              fit="fill"
            ></el-image>
          </div>
        </div>

        <div class="work_bottom_btn">
          <div class="work_bottom_btn_left">
            <el-button plain type="danger" round
            @click="workPospone(work.workId)"
              ><i class="el-icon-bell"></i> 请求延期</el-button
            >
          </div>

          <div class="work_bottom_btn_right">
            <el-button type="primary" round @click="setTheSubmitInfo(work)"
              ><i class="el-icon-upload2"></i> submit</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <div class="submit-div" v-show="submitShow">
      <div class="sign-close" @click="submitShow = false">
        <i class="el-icon-circle-close"></i>
      </div>

      <div class="work_info">
        <div class="work_info_header">
          {{ submitWorkInfo.workName }} - 课程名：{{
            submitWorkInfo.courseName
          }}
          <br />
          <i class="el-icon-time"></i> 开始时间：{{ submitWorkInfo.startTime }}
          <br />
          <i class="el-icon-time"></i> 结束时间：{{ submitWorkInfo.endTime }}
          <br />
          <el-tag>{{
            submitWorkInfo.workType == 1 ? "文本题" : "选择题"
          }}</el-tag>
        </div>

        <div class="ql-snow" v-if="submitWorkInfo.contentType == 1">
          <div class="ql-editor" v-html="submitWorkInfo.content"></div>
        </div>

        <div class="submit-work-content">

            <div v-if="submitWorkInfo.contentType == 2" style="margin-top: 10px">
              <el-image
                :src="submitWorkInfo.workImgUrl"
                :preview-src-list="[submitWorkInfo.workImgUrl]"
                fit="fill"
              ></el-image>
            </div>

            <div v-if="submitWorkInfo.workType == 1" class="submit-text">
              <el-radio-group
                size="medium"
                style="margin-bottom: 10px"
                v-model="submitInfo.contentType"
                @change="changeSubmitType(submitInfo.contentType)"
              >
                <el-radio-button :label="1">文本</el-radio-button>
                <el-radio-button :label="2">图片</el-radio-button>
              </el-radio-group>

              <problem-editor @editorContent="getContent" v-if="submitEditorShow"></problem-editor>

              <div class="avater-div" v-if="submitImgShow">
                <el-upload
                  class="work-file-uploader"
                  action
                  :show-file-list="false"
                  v-model="submitInfo.workImgUrl"
                  :before-upload="beforeAvatarUpload"
                  :http-request="getImgPutUrlFromSts"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="work-file" />
                  <i v-else class="el-icon-plus work-file-uploader-icon"></i>
                </el-upload>
              </div>
            </div>

            <div v-if="submitWorkInfo.workType == 2">
              <div
                v-for="(checkInfo, index) in submitWorkInfo.checkItems"
                :key="index"
                class="checkInfo-item"
                style="margin-top: 1%"
              >
                <div class="checkInfo-item-label">
                  {{checkInfo.label}}：{{ checkInfo.content}}
                </div>
                
                <el-radio
                  style="margin-left: 2%"
                  border
                  v-if="!submitWorkInfo.isMuitlSelect"
                  v-model="submitInfo.check"
                  :label="checkInfo.label"
                  >选择</el-radio
                >

                <el-checkbox
                  border
                  style="margin-left: 2%"
                  v-if="submitWorkInfo.isMuitlSelect"
                  :label="checkInfo.label"
                  v-model="submitInfo.checkList"
                  >选择</el-checkbox
                >
              </div>
            </div>
        </div>


        <el-button type="primary" 
        @click="submitWork"
        round class="submit-btn">提交</el-button>
      </div>
    </div>

  </div>
</template>

<script>
import * as API from "../api/work/index";
import * as FILEAPI from "../api/file/index";
import UUID from "uuidjs";

import "quill/dist/quill.snow.css";
import ProblemEditor from "../components/ProblemEditor.vue";

export default {
  components: { ProblemEditor },
  data() {
    return {
      finishRating:0,
      submitShow: false,
      submitImgShow: false,
      submitEditorShow: true,
      searchValue: "",
      works: [],
      works_1: [],
      works_2: [],
      works_3: [],
      submitWorkInfo: {},
      submitInfo: {
        content: "",
        contentType: 1,
        workId: "",
        workImgUrl: "",
        check:'',
        checkList:[],
      },
      imageUrl: "",
      noDoImgUrl: require("../../public/img/uncommited.png"),
      allImgUrl: require("../../public/img/all.png"),
      doneImgUrl: require("../../public/img/commited.png"),
      searchImgUrl: require("../../public/img/search5.png"),
      timoutImgUrl: require("../../public/img/timeout.png"),
      workImgUrl: require("../../public/img/work5.png"),
    };
  },
  methods: {
    workPospone(workId) {
      API.workPostpone(workId).then(res => {
         if (res.code == 200) {
            this.$notify({
              title: '成功',
              message: res.data.info,
              type: 'success'
            });
          } else {
            this.$message.error(res.data.info);
            return;
          }
      })
      .catch((err) => {
          this.$message.error("网络错误, err:" + err);
        });
    },
    getData(type) {
      API.getMyCourses(type)
        .then((res) => {
          if (res.code == 200) {
            this.works = res.data.works;
            this.finishRating = Math.floor(res.data.finishRating * 10000 ) / 100
          } else {
            this.$message.error(res.data.error);
            return;
          }
        })
        .catch((err) => {
          this.$message.error("网络错误, err:" + err);
        });
    },
    sliceWork(startIndex, workIndex) {
      new Promise((resolve) => {
        // 一段耗时的异步操作
        // reject('失败') // 数据处理出错
        let newWork = [];

        let k = 0;
        for (let i = startIndex; i < this.works.length; i = i + 3) {
          newWork[k++] = this.works[i];
        }

        resolve(newWork); // 数据处理完成
      }).then((res) => {
        //res 为 resolve传递的参数
        if (workIndex === 1) {
          this.works_1 = res;
        } else if (workIndex === 2) {
          this.works_2 = res;
        } else {
          this.works_3 = res;
        }
      });
    },
    searchWorkByCourseName() {
      API.getWorkByCourseName(this.searchValue)
        .then((res) => {
          if (res.code == 200) {
            this.works = res.data.works;
          } else {
            this.$message.error(res.data.error);
            return;
          }
          this.searchValue = "";
        })
        .catch((err) => {
          this.$message.error("网络错误, err: " + err);
        });
    },
    setTheSubmitInfo(work) {
      if (work.workType == 2 && work.isJson == undefined) {
        work.checkInfos = JSON.parse(work.checkInfos)
        work.isJson  = true
        console.log(work.checkInfos.isMuitlSelect)
        work.isMuitlSelect = work.checkInfos.isMuitlSelect
        work.checkItems = work.checkInfos.checkItem
      }
      this.submitWorkInfo = work
      this.submitShow = true
      this.submitInfo.workId = this.submitWorkInfo.workId

    },
    getContent(content) {
      this.submitInfo.content = content
    },
    changeSubmitType(type) {
      if (type == 1) {
        this.submitEditorShow = true;
        this.submitImgShow = false;
      } else {
        this.submitEditorShow = false;
        this.submitImgShow = true;
      }
    },
    getImgPutUrlFromSts(option) {
      let fileName = UUID.generate();
      // let fileName = 'avater7'
      let fileType = option.file.type.split("/")[1];
      FILEAPI.getImgUrl(fileName, fileType)
        .then((res) => {
          let url = res.data.URL;

          const oReq = new XMLHttpRequest();
          oReq.open("PUT", url, true);
          oReq.setRequestHeader("Content-Type", "application/octet-stream");
          oReq.setRequestHeader("x-oss-meta-author", "nothing");
          oReq.send(option.file);
          oReq.onload = () => {
            this.imageUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
            this.submitInfo.workImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
          };
        })
        .catch((error) => {
          this.$notify.error({
            title: "网路错误，或者服务器宕机",
            message: error,
          });
        });
    },
    beforeAvatarUpload(file) {
      console.log(file.type);
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    },
    submitWork() {
      API.submitWork(this.submitInfo).then(res => {
         if (res.code == 200) {
            this.$message({
              message: res.data.info,
              type: 'success'
            });
          } else {
            this.$message.error(res.data.error);
          }

          //清空基本信息。
          this.submitInfo.content = ""
          this.submitInfo.check = ""
          this.submitInfo.checkList = []
          this.submitInfo.workImgUrl = ""
          this.submitInfo.contentType = 1
          
      })
    }
  },
  mounted() {
    this.getData("uncommited");
  },
};
</script>

<style>
#work_view {
  width: 100%;
  min-height: 1000px;
  margin-top: 8%;
  margin-right: 0%;
  display: flex;
  flex-direction: column;
  align-items: center;

  border-top-left-radius: 40px;
  border-top-right-radius: 40px;
  background-color: whitesmoke;
  padding-bottom: 10px;
}

.work_progress {
  padding-top: 12px;
  margin-right: 20%;
  width: 250px;
  flex: 0.85;
}

.work_search_model {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: -2%;
}

.work_search {
  width: 50px;
  height: 50px;
  background-color: white;
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 13%);
  border-radius: 35px;
  margin-right: 2%;
  transition: all 0.4s;

  display: flex;
  justify-content: flex-end;

  background-color: #f6e6fe;
}

.work_search:hover {
  width: 230px;
}

.work_search:hover .work_search_input {
  display: inline-block;
}

.work_search_input {
  min-width: 50%;
  height: 100%;
  text-align: center;
  display: none;
}

.work_search_input > input {
  width: 90%;
  outline: medium;
  margin-top: 7px;
  margin-left: 4%;
  height: 70%;
  border-radius: 35px;
  border: none;
  font-size: 16px;
  vertical-align: text-top;
  background-color: #f6e6fe;
}

.work_search_img {
  width: 50px;
  height: 50px;
  border-radius: 35px;
}

.work_search_img > img {
  width: 50px;
  height: 51px;
  border-radius: 35px;
  margin-top: -0.5px;
}

.work_search_btn {
  width: 50px;
  height: 50px;
  background-color: white;
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 13%);
  border-radius: 50%;
  margin-right: 2%;
}

.work_search_btn:hover {
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 2%);
}

.work_search_btn > img {
  border-radius: 50%;
  width: 50px;
  height: 50px;
}

.work_main {
  width: 94vw;
  /* min-height: 1000px; */
  /* min-height: 1000px;

  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 3%; */
  margin-top: 3%;
  columns: 3;
  column-gap: 30px;
  row-gap: 30px;
  column-fill: auto;
}

.column {
  display: flex;
  flex-direction: column;
  margin-right: 8.5%;
  margin-left: 0%;
}

.item {
  break-inside: avoid;
  transform: translateZ(0);

  margin-bottom: 30px;
  padding: 4% 7%;
  min-width: 320px;
  max-width: 650px;
  min-height: 220px;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 10%);

  word-wrap: break-word;
  word-break: normal;
}

.work_btn {
  position: relative;
  bottom: 2%;
  width: 100%;
  height: 100%;
}

.work_top_img {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 132;
  /* background-color: teal; */
}

.work_top_img > img {
  width: 100%;
  height: 100%;
  background-repeat: "no-repeat";
  background-size: "cover";
}

.work_info {
  /* min-height: 78%; */
  margin-top: 2%;
  display: flex;
  flex-direction: column;
}

.work_timout {
  filter: grayscale(100%);
}

.work_info_header {
  /* text-align: center; */
  padding-left: 15px;
}

.work_bottom_btn {
  /* position: absolute; */
  display: flex;
  justify-content: space-around;
  /* background-color: teal; */
  height: 40px;
  /* line-height: 40px; */
  /* bottom: 50%; */
  /* top: 10%; */
  width: 100%;
  margin-top: 10px;
  margin-bottom: 10px;
}

.submit-div {
  padding: 2%;
  top: calc(20vh);
  width: 600px;
  min-height: calc(40vh);
  max-height: calc(60vh);
  border-radius: 15px;
  background-color: white;
  overflow: auto;
  position: fixed;
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 12%);
}

.sign-close {
  position: absolute;
  width: 25px;
  height: 25px;
  font-size: 20px;
  right: 2%;
  cursor: pointer;
  top: 18px;
}

.submit-text .ql-editor {
  height: 100px;
}

.work-file-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.work-file-uploader .el-upload:hover {
  border-color: #fed049;
}
.work-file-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 320px;
  height: 170px;
  line-height: 170px;
  text-align: center;
}

.checkInfo-item {
  margin-top: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkInfo-item-label {
  width: 250px;
  word-wrap: break-word;
}

.work-file {
  width: 320px;
  height: 170px;
  display: block;
}

.submit-work-content {
  padding-left: 15px;
}

.submit-btn {
  /* margin: 8px; */
  margin-left: 7px;
  margin-top: 10px;
}
</style>